set nocompatible                     " 取消vi兼容
filetype plugin indent on            " 打开文件类型检测并在runtimepath中加载插件配置与缩进
if !exists("g:syntax_on") | syntax enable | endif   " 代码语法高亮

set number                           " 显示行号
set relativenumber                   " 显示相对行号（相对当前光标所在行）
set ruler                            " 右下角显示当前光标位置行列号
set showmatch                        " 自动高亮对应另一半括号
set hlsearch                         " 搜索高亮
set incsearch                        " 每输入一个字符就自动搜索
set laststatus=1                     " 打开2个及以上buffer时显示底边状态栏
set timeoutlen=200 ttimeoutlen=0     " 设置映射延时为300ms，键码延时为0ms
autocmd InsertEnter * set cursorline    " 进入Insert模式时高亮光标所在行
autocmd InsertLeave * set nocursorline  " 推出Insert模式时取消高亮光标所在行

set autochdir                        " 自动切换工作目录
set scrolloff=5                      " 光标距窗口上下保留5行
set mouse=a                          " 允许鼠标在normal模式和visual模式下工作
set backspace=indent,eol,start       " 使用<Backspace>删除
let &termencoding=&encoding          " 解决编码造成的显示乱码问题
set fileencodings=utf-8,gbk,gb2312,gb18030      " 设置写入文件时所支持的文件编码类型

" 以下4行强制将Tab转换成4个空格，可用Ctrl-V<Tab>插入真正的Tab
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4

au BufReadPost * if line("'\"")>1 && line("'\"")<=line("$") | exe "normal! g'\"" | endif


" ==========================================================================

call plug#begin('$VIM/other_plugin')

" 让Vim支持使用neovim插件
Plug 'roxma/nvim-yarp'
Plug 'roxma/vim-hug-neovim-rpc'

Plug 'Shougo/defx.nvim'
Plug 'Yggdroot/LeaderF',{'do':'./install.sh'}
Plug 'neoclide/coc.nvim',{'branch':'release'}
"Plug 'neomake/neomake' 
Plug 'skywind3000/asyncrun.vim'
Plug 'Shougo/neosnippet.vim' | Plug 'Shougo/neosnippet-snippets'

Plug 'tpope/vim-fugitive'
Plug 'lervag/vimtex'
Plug 'tell-k/vim-autopep8'

"Plug 'lyokha/vim-xkbswitch'    " 切换中英文
Plug 'Yggdroot/indentLine'     " 缩进线
Plug 'morhetz/gruvbox'         " 配色方案
call plug#end()

" ==========================================================================

" Plug configure
" -------------------

" #### 1. defx.conf ####
nmap <silent> <F2> :Defx<CR><C-w><C-P>
call defx#custom#option('_', {
      \ 'winwidth':23,
      \ 'split': 'vertical',
      \ 'direction': 'topleft',
      \ 'show_ignored_files': 0,
      \ 'buffer_name': 'index',
      \ 'toggle': 1,
      \ 'resume': 1,
      \ 'auto_cd':1
      \ })

call defx#custom#column('icon', {
      \ 'directory_icon': '▸',
      \ 'opened_icon': '▾',
      \ 'root_icon': ' ',
      \ })

autocmd FileType defx call s:defx_my_settings()
function! s:defx_my_settings() abort
    nnoremap <silent><buffer><expr> <CR> defx#do_action('drop','edit')
    
    nnoremap <silent><buffer><expr> i defx#do_action('drop','edit')
    nnoremap <silent><buffer><expr> m defx#do_action('move')
    nnoremap <silent><buffer><expr> c defx#do_action('copy')
    nnoremap <silent><buffer><expr> p defx#do_action('paste')
    nnoremap <silent><buffer><expr> r defx#do_action('rename')
    nnoremap <silent><buffer><expr> d defx#do_action('remove_trash')
    nnoremap <silent><buffer><expr> N defx#do_action('new_multiple_files')
    nnoremap <silent><buffer><expr> yy defx#do_action('yank_path')

    nnoremap <silent><buffer><expr> ~ defx#do_action('cd')
    nnoremap <silent><buffer><expr> h defx#do_action('cd', ['..'])
    nnoremap <silent><buffer><expr> j line('.') == line('$') ? 'gg' : 'j'
    nnoremap <silent><buffer><expr> k line('.') == 1 ? 'G' : 'k'
    nnoremap <silent><buffer><expr> l defx#do_action('drop','edit')

    nnoremap <silent><buffer><expr> . defx#do_action('toggle_ignored_files')
    nnoremap <silent><buffer><expr> o defx#do_action('open_tree', 'toggle')
    nnoremap <silent><buffer><expr> C defx#do_action('toggle_columns', 
              \ 'mark:indent:icon:filename:type:size:time')
    nnoremap <silent><buffer><expr> S defx#do_action('toggle_sort', 'time')
    nnoremap <silent><buffer><expr> <C-l> defx#do_action('redraw')
    nnoremap <silent><buffer><expr> <C-g> defx#do_action('print')

    nnoremap <silent><buffer><expr> <Space> defx#do_action('toggle_select') . 'j'
    nnoremap <silent><buffer><expr> * defx#do_action('toggle_select_all')
    nnoremap <silent><buffer><expr> R defx#do_action('change_vim_cwd')
    nnoremap <silent><buffer><expr> q defx#do_action('quit')
endfunction


" #### 2. LeaderF.conf ####
let g:Lf_WindowPosition='right'


" #### 3. coc.conf ####
inoremap <silent><expr> <TAB>
            \ pumvisible() ? "\<C-n>" :
            \ <SID>check_back_space() ? "\<TAB>" :
            \ coc#refresh()

function! s:check_back_space() abort
    let col = col('.') - 1
    return !col || getline('.')[col - 1]  =~# '\s'
endfunction


" #### 4. asyncrun.conf ####
function! RunProgram()
    if &filetype == 'python'
        exec "AsyncRun -raw time python3 %"
    elseif &filetype == 'markdown'
        exec "AsyncRun google-chrome --app=file://%:p --enable-features=OverlayScrollbar"
    endif
endfunction
nmap <silent><F5> :call RunProgram()<CR>
nmap <silent><F3> :copen<CR><C-w>L<C-w><C-P>
let $PYTHONUNBUFFERED=1


" #### 5. neosnippet ####
let g:neosnippet#enable_snipmate_compatibility = 1
let g:neosnippet#snippets_directory='~/.vim/mysnippets'
imap <C-j>     <Plug>(neosnippet_expand_or_jump)
smap <C-j>     <Plug>(neosnippet_expand_or_jump)
xmap <C-j>     <Plug>(neosnippet_expand_target)
imap jj \
nmap ;w :w<CR>
nmap ;q :q<CR>


" #### 7. vimtex.conf
let g:tex_flavor = 'latex'
let g:vimtex_view_method = 'zathura'
let g:vimtex_quickfix_mode = 1
let g:vimtex_compiler_latexmk_engines = {'_':'-xelatex'}
let g:vimtex_compiler_tectonic = {
        \ 'build_dir' : '',
        \ 'options' : [
        \ '--keep-logs',
        \ '--synctex'
        \ ],
        \}
let g:vimtex_compiler_latexrun = {
        \ 'build_dir' : '',
        \ 'options' : [
        \   '-verbose-cmds',
        \   '--latex-args="-synctex=1"',
        \   '--shell-escape',
        \ ],
        \}
    let g:vimtex_compiler_latexmk = {
        \ 'build_dir' : '',
        \ 'callback' : 1,
        \ 'continuous' : 1,
        \ 'executable' : 'latexmk',
        \ 'hooks' : [],
        \ 'options' : [
        \   '-verbose',
        \   '-file-line-error',
        \   '-synctex=1',
        \   '-interaction=nonstopmode',
        \   '--shell-escape',
        \ ],
        \}
autocmd VimLeavePre *.tex call system("latexmk -c && rm *.xdv") 
""let g:vimtex_quickfix_ignore_filters = [
""            \ 'zhlineskip Warning',
""            \ 'fontspec Warning', 
""            \ 'xeCJK Warning',
""            \ 'Fancyhdr Warning',
""            \]

nmap <silent><F6> :call ResetConceallevel()<CR>
function! ResetConceallevel()
    if &conceallevel==0
        exec "set conceallevel=2"
    else
        exec "set conceallevel=0"
    endif
endfunction


" #### 9. ibus.conf ####
""let g:XkbSwitchEnabled = 1
""let g:XkbSwitchLib='/usr/local/lib/libg3kbswitch.so'
""let g:XkbSwitchNLayout = 'us'
""autocmd InsertEnter * let g:XkbSwitchILayout = 'cn'


" #### 10. indentLine.conf #### 
let g:indentLine_color_term = 243


" #### 11. gruvbox.conf ####
colorscheme gruvbox
set background=dark
let g:gruvbox_contrast_dark='medium'
hi Normal ctermfg=252 ctermbg=none


" ==========================================================================

function! AddTitle()
    if &filetype == 'python'
        call append(0, "#!/usr/bin/env python3")
        call append(1, "# -*- coding:utf-8 -*-")
        call append(2, "")
    endif
endfunction

" #### 括号、引号补全 ####
inoremap ( ()<ESC>i
inoremap [ []<ESC>i
inoremap { {}<ESC>i
inoremap ' ''<ESC>i
inoremap " ""<ESC>i
inoremap """ """<CR>"""<ESC>O

function! SkipPair()
    let current_char = getline('.')[col('.')-1]
    if current_char == (")" || "]" || "}" || "'" || '"')
        return "\<ESC>la"
    endif
endfunction
inoremap <silent> <C-k> <C-r>=SkipPair()<CR>



let g:input_toggle = 0
function! Fcitx2en()
let s:input_status = system("fcitx-remote")
if s:input_status == 2
let g:input_toggle = 1
let l:a = system("fcitx-remote -c")
endif
endfunction

function! Fcitx2zh()
let s:input_status = system("fcitx-remote")
if s:input_status != 2 && g:input_toggle == 1
let l:a = system("fcitx-remote -o")
let g:input_toggle = 0
endif
endfunction
autocmd InsertLeave * call Fcitx2en()
autocmd InsertEnter * call Fcitx2zh()
autocmd VimLeavePre * call system("fcitx-remote -o")



